import jwt from 'jsonwebtoken';
import { getUserById } from '~/server/database/services/userService';

// JWT密钥，生产环境中应该使用环境变量
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';

export interface JWTPayload {
  userId: number;
  username: string;
  iat?: number;
  exp?: number;
}

/**
 * 生成JWT token
 * @param userId 用户ID
 * @param username 用户名
 * @returns JWT token字符串
 */
export const generateToken = (userId: number, username: string): string => {
  const payload: Omit<JWTPayload, 'iat' | 'exp'> = {
    userId,
    username,
  };

  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: JWT_EXPIRES_IN,
  });
};

/**
 * 验证JWT token
 * @param token JWT token字符串
 * @returns 解析后的payload或null
 */
export const verifyToken = (token: string): JWTPayload | null => {
  try {
    const decoded = jwt.verify(token, JWT_SECRET) as JWTPayload;
    return decoded;
  } catch (error) {
    console.error('Token验证失败:', error);
    return null;
  }
};

/**
 * 从请求头中提取token
 * @param authHeader Authorization请求头
 * @returns token字符串或null
 */
export const extractTokenFromHeader = (authHeader: string | undefined): string | null => {
  if (!authHeader) {
    return null;
  }

  const parts = authHeader.split(' ');
  if (parts.length !== 2 || parts[0] !== 'Bearer') {
    return null;
  }

  return parts[1];
};

/**
 * 根据token获取用户信息
 * @param token JWT token
 * @returns 用户信息或null
 */
export const getUserFromToken = async (token: string) => {
  const payload = verifyToken(token);
  if (!payload) {
    return null;
  }

  const user = await getUserById(payload.userId);
  if (!user) {
    return null;
  }

  return {
    ...user.toJSON(),
    // 移除敏感信息
    password: undefined,
  };
};
